﻿using MXERP.Infrastructure.Managers;
using MXERP.Shared.Extensions;

namespace MXERP.Infrastructure.Store
{
    public partial class RouteState
    {
        public static class Init
        {
            public record Action() : IAction;

            public class Handler : ActionHandler<Action>
            {
                private readonly IAppManager _appManager;
                public Handler(IStore store, IAppManager appManager) : base(store)
                {
                    _appManager = appManager;
                }

                RouteState RouteState => Store.GetState<RouteState>();

                public override async Task Handle(Action aAction, CancellationToken aCancellationToken)
                {
                    var result = await _appManager.GetCurrentUserApps();
                    var routes = new List<Route>();
                    foreach (var app in result.Data)
                    {
                        var route = new Route()
                        {
                            Id = app.Id,
                            PId = app.PId,
                            Type = app.Type,
                            Name = app.Name,
                            Path = app.Path,
                            License = app.License,
                            Icon = app.Icon,
                            Title = app.Title,
                            IsHide = app.IsHide,
                            IsKeepAlive = app.IsKeepAlive,
                            IsAffix = app.IsAffix,
                            IsMultiTab = app.IsMultiTab,
                            Sort = app.Sort,
                        };
                        routes.Add(route);
                    }
                    RouteState.Routes = routes;
                    RouteState.RouteTree = routes.ToTree();
                    RouteState.IsInit = true;
                }
            }
        }
    }
}
